##Replication code for "drivers of resemblance: explaining the conversion of pre-electoral coalitions
##into coalition cabinets"
library(QCA)
library(tidyverse)
library(ragg)
library(SetMethods)
library(showtext)

sec <- read.csv("dpr.csv", sep=";")


##Calibration Process----
sec1 <- sec %>%
        filter(type == "pre") %>%
        select(-type, -legislative_type, -inter_party_primaries,
               -low_chamber, -upp_chamber, -status, -country, -ce) %>%
        column_to_rownames(var = "cases")

sec2 <- sec1 %>%
        mutate(lwpol = calibrate(lwpol, type = "fuzzy", method = "direct", threshold = "e=3, c=2, i=1")) %>%
        mutate(hlpol = calibrate(hlpol, type = "fuzzy", method = "direct", threshold = "e=1.5, c=2.7, i=4")) %>%
        mutate(htemp = calibrate(htemp, type = "fuzzy", method = "direct", threshold = "e=85, c=70, i=55")) %>%
        mutate(lplp = calibrate(lplp, type = "fuzzy", method = "direct", threshold = "e=0.5, c=0.405, i=0.3")) %>%
        rename(LWPOL = lwpol,
               MAJ = maj, 
               HLPOL = hlpol,
               HTEMP = htemp,
               LPP = lplp,
               CR = cr)

##The code below produces Table A.2 in the Supplementary Material
write.table(sec2, "calibrated_ds.csv", sep=";", col.names=NA)

##Skewness Check #Ideally not more than a 4:1 ratio----
skew.check(sec2$MAJ)
skew.check(sec2$LWPOL)
skew.check(sec2$HLPOL)
skew.check(sec2$LPP)
skew.check(sec2$HTEMP)
skew.check(sec2$CR)

##Analysis of Necessity----
##The code below produces Table 2 in the main document.
superSubset(sec2, 
            outcome = "CR",
            incl.cut = 0.9,
            ron.cut = 0.6)

##Analysis of Sufficiency----
##The code below produces Table 3 in the main document. Notice that logical remainder rows are omitted from the table. 
TTsec <- truthTable(sec2, outcome = "CR",
                    complete = TRUE, incl.cut = 0.8,
                    sort.by = "incl, n+",
                    show.cases = TRUE)

stargazerTT(TTsec,
            show.cases = T,
            type = "text")

ESA <- findRows("~MAJ*~HTEMP", obj = TTsec)

##The code below produces Table 4 in the main document.
intermediate_result <- minimize(TTsec, include = "?", details = TRUE, dir.exp = "1,1,1,1,1", exclude = ESA)

stargazerSol(intermediate_result, 
             outcome = "CR",
             show.cases = T,
             type = "latex")

factorize(input = "MAJ*LWPOL + ~LWPOL*HLPOL*HTEMP + HLPOL*HTEMP*LPP + LWPOL*HLPOL*~HTEMP*~LPP",
          snames = "MAJ, LWPOL, HLPOL, LPP, HTEMP")